<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>实时音频输入</title>
</head>
<body>
    <h1>实时音频录制</h1>
    <button id="startButton">开始录音</button>
    <button id="stopButton" disabled>停止录音</button>

    <script>
        const startButton = document.getElementById('startButton');
        const stopButton = document.getElementById('stopButton');
        let mediaRecorder;
        let socket;

        // 点击“开始录音”按钮，初始化 WebSocket 和 MediaRecorder
        startButton.addEventListener('click', async () => {
            // 打开 WebSocket 连接
            socket = new WebSocket('ws://localhost:8000/ws/audio/');

            socket.onopen = () => {
                console.log("WebSocket 连接已打开");
            };

            socket.onclose = () => {
                console.log("WebSocket 连接已关闭");
            };

            // 获取麦克风音频流
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            mediaRecorder = new MediaRecorder(stream);

            // 处理音频数据
            mediaRecorder.ondataavailable = (event) => {
                if (socket.readyState === WebSocket.OPEN) {
                    socket.send(event.data);
                }
            };

            mediaRecorder.start(100); // 每100ms发送音频片段
            startButton.disabled = true;
            stopButton.disabled = false;
        });

        // 点击“停止录音”按钮，停止录音并关闭 WebSocket
        stopButton.addEventListener('click', () => {
            mediaRecorder.stop();
            socket.close();
            startButton.disabled = false;
            stopButton.disabled = true;
        });
    </script>
</body>
</html>
